package com.xb.test.utils;

import javax.servlet.http.HttpServletRequest;

public class IPAddrUtils {
    public static String getIpAddr(HttpServletRequest req) {
//        String ip = req.getHeader("x-forwarded-for");
//        if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
//            ip = req.getHeader("Proxy-Client-IP");
//        }
//        if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
//            ip = req.getHeader("WL-Proxy-Client-IP");
//        }
//        if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
//            ip = req.getRemoteAddr();
//            if (ip.equals("127.0.0.1")) {
//                InetAddress inet = null;
//                try {
//                    inet = InetAddress.getLocalHost();
//                } catch (UnknownHostException e) {
//                    e.printStackTrace();
//                }
//                ip = inet.getHostAddress();
//            }
//        }
//        if ((ip != null) && (ip.length() > 15) &&
//                (ip.indexOf(",") > 0)) {
//            ip = ip.substring(0, ip.indexOf(","));
//        }


        String ip = req.getHeader("x-forwarded-for");

        if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
            ip = req.getHeader("Proxy-Client-IP");
        }
        if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
            ip = req.getHeader("WL-Proxy-Client-IP");
        }
        if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
            ip = req.getRemoteAddr();
        }
        if((ip != null) && (ip.length() > 15) && (ip.indexOf(",") > 0)){
            ip=ip.substring(0,ip.indexOf(","));
        }
        return ip;
    }
}
